package com.jieyun.core.utils;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 异常处理工具类
 * @author trekxu
 */
public abstract class ExceptionUtils {
	
	/**
	 * 将限制性异常转换为非限制性异常
	 * @param e
	 * @return
	 */
	public static final RuntimeException  convertException(Throwable e) {
		return new RuntimeException(e);
	}
	
	/**
	 * 将异常转换为特定的异常类型。
	 * 当具有T(Exception) 的构造函数的时候，抛出参数不正确的异常
	 * @param e
	 * @param requiredClass
	 * @return
	 */
	public static final <T extends RuntimeException>  T convertException(Throwable exception ,Class<T> requiredClass){
		
			Constructor<T> constructor;
			try {
				constructor = requiredClass.getConstructor(Exception.class);
			} catch (NoSuchMethodException | SecurityException e1) {
				throw new IllegalArgumentException("不具有T(Exception)这样的构造函数");
			}
			try {
				return  (T) constructor.newInstance(exception);
			} catch (InstantiationException | IllegalAccessException | IllegalArgumentException
					| InvocationTargetException e) {
				throw new IllegalStateException("初始化失败");
			}
	}  
	
}
